// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.common.lib;

import com.google.api.ads.common.lib.auth.OAuthAuthorizationHeaderProvider;
import com.google.api.ads.common.lib.client.AdsServiceClient;
import com.google.api.ads.common.lib.client.AdsServiceDescriptor;
import com.google.api.ads.common.lib.client.AdsSession;
import com.google.api.ads.common.lib.factory.FactoryModule;
import com.google.api.ads.common.lib.factory.FactoryModule.AdsServiceClientFactoryInterface;
import com.google.api.ads.common.lib.factory.FactoryModule.AdsServiceDescriptorFactoryInterface;
import com.google.api.ads.common.lib.factory.helper.AdsServiceClientFactoryHelper;
import com.google.api.ads.common.lib.utils.logging.LoggingModule;
import com.google.common.annotations.VisibleForTesting;
import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;

import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * Guice module for common bindings.
 *
 * @param <C> the subclass of {@link AdsServiceClient}
 * @param <D> the subclass of {@link AdsServiceDescriptor}
 * @param <S> the subclass of {@link AdsSession}
 *
 * @author Adam Rogal
 */
public class AdsModule <C extends AdsServiceClient<S, D>,
                        D extends AdsServiceDescriptor,
                        S extends AdsSession> extends AbstractModule {


  private Reflections reflections;

  /**
   * Default constructor.
   */
  public AdsModule() {
    reflections = new Reflections(new ConfigurationBuilder()
        .filterInputsBy(new FilterBuilder().include("com\\.google\\.api\\.ads\\..*Module.*"))
        .setUrls(ClasspathHelper.forClassLoader()));
  }

  /**
   * Overloaded constructor for testing.
   */
  @VisibleForTesting
  AdsModule(Reflections reflections) {
    this.reflections = reflections;
  }

  /**
   * Configure common Guice bindings.
   */
  @Override
  protected void configure() {
    configureAuthentication();
  }

  protected void configureAuthentication() {
    bind(OAuthAuthorizationHeaderProvider.class);
    bind(String.class).annotatedWith(Names.named("requestMethod")).toInstance("POST");
  }

  /**
   * Configures which SOAP framework to use.
   *
   * In order for this method to succeed without throwing an
   * {@code IllegalStateException}, at least one of two possible states must
   * exist:
   *
   * 1) A {@code moduleFromFactoryConfiguration} module was specified and can be
   *    instantiated.
   * 2) Exactly one module on the classpath is annotated with
   *    {@code moduleAnnotationClass} and can be instantiated.
   *
   * @param moduleFromFactoryConfiguration the {@code Class} of the SOAP module
   *        to use which was specified in the user's properties file. If no
   *        class was specified, this is expected to be {@code null}.
   * @param moduleAnnotationClass the {@code Annotation} used to mark classes
   *        that are valid modules to use with this product. If no
   *        {@code moduleFromFactoryConfiguration} was specified, the classpath
   *        will be searched for classes with this annotation.
   * @throws IllegalStateException if no SOAP module is available or more than
   *         one SOAP module is available.
   */
  protected void configureSoap(Class<?> moduleFromFactoryConfiguration,
      Class<? extends Annotation> moduleAnnotationClass) {
    Class<?> soapClientHandlerModuleClass = null;
    if (moduleFromFactoryConfiguration != null) {
      soapClientHandlerModuleClass = moduleFromFactoryConfiguration;
    } else {
      Set<Class<?>> modulesOnClasspath = reflections.getTypesAnnotatedWith(moduleAnnotationClass);
      if (modulesOnClasspath.isEmpty()) {
        throw new IllegalStateException("Unable to locate a SOAP module by reflection. " +
            "Did you forget to add a plugin specifying which SOAP framework to use with the " +
            "library?");
      }
      if (modulesOnClasspath.size() > 1) {
        throw new IllegalStateException("Located more than one SOAP module on the " +
            "classpath. Did you add more than one plugin specifying which SOAP framework to " +
            "use with the library?");
      }
      soapClientHandlerModuleClass = modulesOnClasspath.iterator().next();
    }

    try {
      install((AbstractModule) soapClientHandlerModuleClass.newInstance());
    } catch (InstantiationException e) {
      throw new IllegalStateException("Unable to instantiate SOAP module by reflection. " +
          "Did you add the correct plugin specifying which SOAP framework to use with the " +
          "library?", e);
    } catch (IllegalAccessException e) {
      throw new IllegalStateException("Unable to instantiate SOAP module by reflection. " +
          "Did you add the correct plugin specifying which SOAP framework to use with the " +
          "library?", e);
    }
  }

  /**
   * Configures the loggers given the prefix.
   *
   * @param loggerPrefix the logger prefix
   */
  protected void configureLogging(String loggerPrefix) {
    install(new LoggingModule(loggerPrefix));
  }

  /**
   * Configures the factories.
   *
   * @param <H> the subclass of {@link AdsServiceClientFactoryHelper}
   *
   * @param adsServiceClientFactoryTypeLiteral the factory type literal which
   *        contains a {@link AdsServiceClientFactoryInterface}
   * @param adsServiceDescriptorFactoryTypeLiteral the factory type literal
   *        which contains a {@link AdsServiceDescriptorFactoryInterface}
   * @param adsServiceClientTypeLiteral the ads service client literal which
   *        contains a {@link AdsServiceClient}
   * @param adsServiceDescriptorTypeLiteral the ads service descriptor literal
   *        which contains a {@link AdsServiceDescriptor}
   * @param factoryHelperClass the factory helper class
   * @param factoryClass the factory class
   */
  @SuppressWarnings("unchecked") // Guice lacks support for template type literals.
  protected <H extends AdsServiceClientFactoryHelper<C, S, D>>
      void configureFactories(
          @SuppressWarnings("rawtypes") /* Guice lacks support for template type literals.*/
          TypeLiteral adsServiceClientFactoryTypeLiteral,
          @SuppressWarnings("rawtypes") /* Guice lacks support for template type literals.*/
          TypeLiteral adsServiceDescriptorFactoryTypeLiteral,
          @SuppressWarnings("rawtypes") /* Guice lacks support for template type literals.*/
          TypeLiteral adsServiceClientTypeLiteral,
          @SuppressWarnings("rawtypes") /* Guice lacks support for template type literals.*/
          TypeLiteral adsServiceDescriptorTypeLiteral,
          Class<H> factoryHelperClass,
          Class<?> factoryClass) {
    install(new FactoryModule<C, D, S, H>(adsServiceClientFactoryTypeLiteral,
                                             adsServiceDescriptorFactoryTypeLiteral,
                                             adsServiceClientTypeLiteral,
                                             adsServiceDescriptorTypeLiteral,
                                             factoryHelperClass,
                                             factoryClass));
  }
}
